package com.clkj.mobileinspector.ui.activity;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.clkj.mobileinspector.R;
import com.clkj.mobileinspector.model.Constant;
import com.clkj.mobileinspector.utils.RandomStringUtils;
import com.lws.basic.base.BaseActivity;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.MyToast;
import com.lws.basic.utils.common.SharePreferenceUtils;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

//登录
@RuntimePermissions
public class LoginActivity extends BaseActivity {
    //@BindView(R.id.et_account)
//    EditText mEtAccount;
//    @BindView(R.id.et_password)
//    EditText mEtPassword;
    @BindView(R.id.cl_login)
    ConstraintLayout mCl_lgoin;
    private LoginBroadcastReceiver mReceiver;

    @Override
    public int setLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        MyLogger.setLogName();

        //注册 登陆广播
        mReceiver = new LoginBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.clkj.mobileinspector.ACTION_LOGIN");
        intentFilter.addAction("com.clkj.mobileinspector.ACTION_LOGOUT");
        registerReceiver(mReceiver, intentFilter);
//        SharePreferenceUtils.putString(this, "appCredential", "111");
//        SharePreferenceUtils.putString(this,  Constant.userCredential,"11");
        String appCredential = SharePreferenceUtils.getString(this, Constant.appCredential, "");
        String userCredential = SharePreferenceUtils.getString(this, Constant.userCredential, "");
        if (TextUtils.isEmpty(appCredential) || TextUtils.isEmpty(userCredential)) {
            mCl_lgoin.setVisibility(View.VISIBLE);
            LoginActivityPermissionsDispatcher.permissionWithCheck(this);

        } else {
            //startActivity(new Intent(this, MainActivity.class));
            login();
        }

    }

    @OnClick(R.id.btn)
    public void onViewClicked() {
        login();

    }

    /**
     * 登录
     */
    private void login() {
        try {
            showLoading("登录中");
            //1获取用户凭证  IF-UA-SDK-01
            Uri uri = Uri.parse("content://com.ydjw.ua.getCredential");
            ContentResolver resolver = getContentResolver();
            Bundle params = new Bundle();
            String messageId = RandomStringUtils.getRandomString(32);//32位随机字符串
            params.putString("messageId", messageId);
            params.putString("version", "1"); //当前接口版本
            params.putString("appId", Constant.AppId);//应用 ID，由应用注册者提供，应用在 MDP 注册后生成120000000000-3-1-d74158ff4a5046609748157503252bee
            params.putString("orgId", Constant.orgId);//机构 ID，等同 regionalismCode。 120000000000
            params.putString("networkAreaCode", "3");//网络区域码，等同 networkCode。
            params.putString("packageName", "com.clkj.mobileinspector");//应用包名
            MyLogger.i("登录参数: "+ params.toString());
            Bundle bundle = resolver.call(uri, "", null, params);//call 方式调用，返回值为 Bundle 对象

            if (bundle != null) {
                String msgId = bundle.getString("messageId");
                String version = bundle.getString("version");
                int resultCode = bundle.getInt("resultCode");//0:成功, -3: 参数错误；-5: 凭证不存在 三方应用应等待统一认证去后台获取凭证
                String message = bundle.getString("message");//错误码对应的文字信息描述
                String userCredential = bundle.getString("userCredential");//用户凭证appCredential
                String appCredential = bundle.getString("appCredential");//应用凭证
                MyLogger.i("登录返回值");
                MyLogger.i("messageId：" + msgId);
                MyLogger.i("version：" + version);
                MyLogger.i("resultCode：" + resultCode);
                MyLogger.i("message：" + message);
                MyLogger.i("resultCode：" + resultCode);
                MyLogger.i("userCredential：" + userCredential);
                MyLogger.i("appCredential：" + appCredential);
                SharePreferenceUtils.putString(this, "version", version);
                SharePreferenceUtils.putString(this, Constant.appCredential, appCredential);
                SharePreferenceUtils.putString(this, Constant.userCredential, userCredential);
                dismissLoading();
                if (resultCode == 0) {
                    MyToast.show("登录成功");
                    startActivity(new Intent(this, MainActivity.class));
                    finish();
                } else {
                    MyToast.show(resultCode + message);
                }

            } else {
                MyLogger.i("获取应用凭证失败,bundle为空");
                MyToast.show("获取应用凭证失败,bundle为空");
            }
        } catch (Exception e) {
            MyLogger.i(e.getMessage());
            MyToast.show(e.getMessage());
        }
    }



    /**
     * 获取文件写入权限
     */

    @NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
    void permission() {
    }

    /**
     * 权限回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public class LoginBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            MyLogger.i("广播:"+intent.getAction());
            //登录
            if (intent.getAction().equals("com.clkj.mobileinspector.ACTION_LOGIN")) {
                MyLogger.i("登录："+intent.getAction());
                login();

            }
            //退出
            if (intent.getAction().equals("com.clkj.mobileinspector.ACTION_LOGOUT")) {
                MyLogger.i("退出："+intent.getAction());
                SharePreferenceUtils.putString(LoginActivity.this, Constant.appCredential, "");
                SharePreferenceUtils.putString(LoginActivity.this, Constant.userCredential, "");
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceiver);
    }
}
